package student;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class FileUtils {
	
	private static final String FILE_NAME = "student.txt";
	
	public static boolean writeToFile(List<Student> studentList) {
		try (FileOutputStream fos = new FileOutputStream(FILE_NAME);
			ObjectOutputStream oos = new ObjectOutputStream(fos);){
			oos.writeObject(studentList);
			oos.flush();
			System.out.println("写完成");
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public static List<Student> readFromFile(){
		// 1.创建文件
		File f = new File(FILE_NAME);
		// 2.判断文件是否存在
		if (f.exists()) {
			try (FileInputStream fos = new FileInputStream(FILE_NAME);
				ObjectInputStream oos = new ObjectInputStream(fos);){
				
				return (List<Student>) oos.readObject();
				
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
		return new ArrayList<>();
	}
}
